import { defineConfig, splitVendorChunkPlugin } from 'vite';
import vue from '@vitejs/plugin-vue';
import { join, resolve } from 'path';
import { existsSync, readFileSync } from 'node:fs';
import { spawn, execSync, exec } from 'node:child_process';
import { setDefaultResultOrder } from 'dns';

setDefaultResultOrder('verbatim');
export default defineConfig({
  plugins: [vue(), splitVendorChunkPlugin()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '~': resolve(__dirname, 'src'),
      // '@': 'src',
    },
  },
  server: {
    https: generateCerts(),
    proxy: {
      // proxy API requests to the ASP.NET backend d
      '/api': {
        // changeOrigin: true,
        secure: false,
        // rewrite: (path) => path.replace(/^\/api/, '/api'),
        // target taken from src/setupProxy.js in ASP.NET React template
        target: process.env.ASPNETCORE_HTTPS_PORT
          ? `https://localhost:${process.env.ASPNETCORE_HTTPS_PORT}`
          : process.env.ASPNETCORE_URLS
          ? process.env.ASPNETCORE_URLS.split(';')[0]
          : 'https://localhost:5173',
      },
    },
  },
  build: {
    emptyOutDir: true,
    outDir: '../../Services/Pesticide/Pesticide.API/wwwroot',
    target: 'esnext',
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        /**
         * 分割模块
         * @param id
         * @returns string
         */
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id
              .toString()
              .split('node_modules/')[1]
              .split('/')[0]
              .toString();
          }
        },
      },
    },
  },
});

/** Function taken from aspnetcore-https.js in ASP.NET React template */
function generateCerts() {
  console.log(process.env.ASPNETCORE_HTTPS_PORT);
  console.log(process.env.ASPNETCORE_URLS);
  const baseFolder =
    process.env.APPDATA !== undefined && process.env.APPDATA !== ''
      ? `${process.env.APPDATA}/ASP.NET/https`
      : `${process.env.HOME}/.aspnet/https`;

  console.log({ baseFolder });

  const certificateArg = process.argv
    .map((arg) => arg.match(/--name=(?<value>.+)/i))
    .filter(Boolean)[0];

  // const certificateName = 'localhost';
  const certificateName = certificateArg
    ? certificateArg.groups.value
    : process.env.npm_package_name;

  console.log({ certificateArg });
  console.log({ certificateName });
  if (!certificateName) {
    console.error(
      'Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.'
    );
    process.exit(-1);
  }

  const certFilePath = join(baseFolder, `${certificateName}.pem`);
  const keyFilePath = join(baseFolder, `${certificateName}.key`);
  console.log({ certFilePath });
  console.log({ keyFilePath });
  console.log(existsSync(certFilePath));

  if (!existsSync(certFilePath) || !existsSync(keyFilePath)) {
    console.log(123);

    // spawn(
    //   'dotnet',
    //   [
    //     'dev-certs',
    //     'https',
    //     '--export-path',
    //     certFilePath,
    //     '--no-password',
    //     '--format',
    //     'Pem',
    //     '--trust',
    //   ],
    //   { stdio: 'inherit' }
    // ).on('exit', (code) => process.exit(code));
    execSync(
      `dotnet dev-certs https --export-path ${certFilePath} --no-password --format Pem --trust`
    );
    // exec(
    //   `dotnet dev-certs https --export-path ${certFilePath} --no-password --format Pem --trust`,
    //   (error, stdout, stderr) => {
    //     if (!error) {
    //       // 成功
    //       console.log('成功');
    //     } else {
    //       // 失败
    //       console.log('失败');
    //     }
    //   }
    // );
  }

  return {
    cert: readFileSync(certFilePath, 'utf8'),
    key: readFileSync(keyFilePath, 'utf8'),
  };
}
